package adminService

import (
	"gitee.com/yangguoliang001/go-gin-vue3/BO"
	"gitee.com/yangguoliang001/go-gin-vue3/QO"
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/response"
	"gitee.com/yangguoliang001/go-gin-vue3/util/code"
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
)

func (a *AdminService) QueryAdminMenu(c *gin.Context, useId int32) (adminMenuList []BO.AdminMenuListBO, err error) {
	// 查询当前用户对应的菜单id列表
	adminMenuIds, err := a.adminMenuDao.WhereMenuIdByAdminId(useId)

	if err != nil {
		return nil, err
	}

	// 查询菜单数据
	menuList, err := a.menuDao.QueryMenuUsedList()
	if err != nil {
		return nil, err
	}

	for _, menuItem := range menuList {
		data := BO.AdminMenuListBO{
			Id:     menuItem.Id,
			Pid:    menuItem.Pid,
			Name:   menuItem.Name,
			IsUsed: 0, // 当前菜单没有被配置
		}
		for _, v := range adminMenuIds {
			if menuItem.Id == v.MenuId {
				data.IsUsed = 1 // 已经被配置
			}
		}
		adminMenuList = append(adminMenuList, data)
	}
	return
}

func (a *AdminService) EditAdminMenu(c *gin.Context, adminMenuReq QO.EditAdminMenuReq) (err error) {
	// 查询当前用户对应的菜单id列表
	adminMenuIds, err := a.adminMenuDao.WhereMenuIdByAdminId(adminMenuReq.Id)

	if err != nil {
		return err
	}
	// 需要修改的 ids
	editIds := strings.Split(adminMenuReq.Actions, ",")
	var addMenuItems []BO.AddAdminMenuBO
	var deletedIds []int32

	for _, v := range adminMenuIds {
		var isDeleted = true
		for _, id := range editIds {
			idInt, _ := strconv.Atoi(id)
			if v.MenuId == int32(idInt) {
				isDeleted = false
			}
		}
		if isDeleted {
			// 如果 adminMenuIds 中有， 但 editIds 中没有， 需要被删除
			deletedIds = append(deletedIds, v.Id)
		}
	}

	for _, id := range editIds {
		idInt, _ := strconv.Atoi(id)
		// 当前 menu 是否被启用
		var isUsed = false
		for _, v := range adminMenuIds {
			if v.MenuId == int32(idInt) { // 都有 不需要 被修改
				isUsed = true
			}
		}
		// 需要被添加
		if !isUsed {
			addItem := BO.AddAdminMenuBO{
				AdminId:     adminMenuReq.Id,
				MenuId:      int32(idInt),
				CreatedUser: "admin",
			}
			addMenuItems = append(addMenuItems, addItem)
		}
	}
	// 删除 或 新增
	err = a.adminMenuDao.EditAdminMenu(addMenuItems, deletedIds)
	if err != nil {
		response.Fail(c, code.AdminMenuCreateError, code.Text(code.AdminCreateError), gin.H{"realErr": err})
		return err
	}

	return nil
}
